<script lang="ts" setup>
// @ts-ignore
import PIXI from "../tools/pixi/pixi-spine.js";
import resizeManager from "../manager/resizeManager";
import { onMounted, onBeforeUnmount, ref } from "vue";
import { onBeforeRouteUpdate, useRoute } from "vue-router";
import DataManager from "../manager/dataManager";
import Message from '../tools/Message';

interface vocData {
    id: string,
    dom: HTMLAudioElement,
}

const route = useRoute();
let curData: any = {};
let curVoc: Array<vocData> = [];

const oldWidth = 3460;
const oldHeight = 2568;
const app = new PIXI.Application({
    backgroundColor: 0xFFFFFF,
    antialias: false,
    width: oldWidth,
    height: oldHeight,
});
app.view.className += "spineDiv";
app.view.setAttribute("id", "spineDiv");

let data: Array<any> = [];

const root = ref<HTMLDivElement>();
const canvas = ref<HTMLCanvasElement>();
const audioDiv = ref<HTMLDivElement>();
let ordylan: any;

onMounted(async () => {
    root.value?.prepend(app.view);
    canvas.value = app.view;
    resizeManager.add('canvasBAHome', resize);
    await loadData();
    const id = route.query.id?.toString()!;
    loadSpine(id);
})

onBeforeRouteUpdate((e) => {
    const id = e.query.id?.toString()!;
    loadSpine(id);
    curVoc = [];
    audioDiv.value!.innerHTML = "";
});

onBeforeUnmount(() => {
    Message.hide('loading');
})

const resize = () => {
    const w = root.value?.clientWidth!;
    const h = root.value?.clientHeight!;
    canvas.value!.width = w;
    canvas.value!.height = h;
    ordylan.scale.set(h / curData.scale);
    ordylan.x = w / 2;
    ordylan.y = h / 2;
}

const loadData = async () => {
    data = await DataManager.get('baData');
}

let actionIndex = 0;
let isAnimPlay = true;


const loadSpine = (id: string) => {
    let curId = id;
    if (!id) {
        curId = 'airi';
    }
    curId = curId.toLocaleLowerCase();
    curData = data.find(u => u.Id == curId);

    Message.show('loading');

    PIXI.loader.resources = {};
    let loader = PIXI.loader.add(curId, `../../public/baData/${curId}/home/${curId}_home.json`);//OD.json你的json

    loader.load((_loader: any, res: any) => {
        ordylan = new PIXI.spine.Spine(res[curId].spineData);

        app.stage.children = [];
        app.stage.addChild(ordylan);
        app.stage.children[0].state.addListener({
            complete: function (_e: any) {
                //执行完的事件
                if (actionIndex == 0) {
                    actionIndex = 1;
                    animPlay();
                }
                const name = _e.animation.name;
                curData.action.forEach((data: any, index: any) => {
                    if (data == name && !(index == 1 || index == 2)) {
                        isAnimPlay = false;
                    }
                });
            },
            event: function (_e: any, a: any) {
                if (a.stringValue)
                    videoPlay(a.stringValue);
            }
        });
        //加载声音
        curVoc = [];
        audioDiv.value!.innerHTML = "";
        curData.voc.forEach((u: string) => {
            const audio = document.createElement('audio');
            audio.pause();
            audio.src = `../../public/baData/${curData.Id}/voc/${u}.ogg`.toLocaleLowerCase()
            curVoc.push({ id: u, dom: audio });
            audioDiv.value?.append(audio);
        })

        actionIndex = 0;
        isAnimPlay = true;
        animPlay();
        resize();

        Message.hide('loading');
    });
}
//眨眼计时器
setInterval(function () {
    if (!isAnimPlay) {
        app.stage.children[0].state.setAnimation(2, curData.action[2], false);
    }
}, 3000);
const animPlay = () => {
    app.stage.children[0].state.setAnimation(actionIndex < 3 ? 0 : 1, curData.action[actionIndex], actionIndex == 1 ? true : false);
}
const anime_ClickEvent = () => {
    if (!isAnimPlay) {
        actionIndex++;
        if (actionIndex < 3) {
            actionIndex = 3;
        }
        if (actionIndex >= curData.action.length) {
            actionIndex = 3;
        }
        isAnimPlay = true;
        animPlay();
    }
}
const videoPlay = (name: string) => {
    const audio = curVoc.find(u => u.id == name.toLocaleLowerCase())?.dom;
    audio!.play();
}




</script>

<template>
    <div ref="audioDiv" class="audio-div"></div>
    <div ref="root" class="canvasBaHome-root" @click="anime_ClickEvent"></div>
</template>

<style scoped lang="scss">
.canvasBaHome-root {
    height: 100%;
    aspect-ratio: 4/3;
    background-color: red;
}
</style>